package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.ums.UmsAdmin;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 *
 *
 * @author DogeGuo
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求参数Authorization
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(token)) {
            //移除token中前缀信息(前端人员添加的)
            token = token.replace("Bearer ", "");
            //从redis中获取admin
            String adminJson = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
            if (StrUtil.isNotBlank(adminJson)) {
                //把JSON数据转换为amin对象
                UmsAdmin admin = JSON.parseObject(adminJson, UmsAdmin.class);
                if (admin != null) {
                    //将admin保存到ThreadLocal中
                    AdminHolder.set(admin);

                    //重置token保存在redis中时间,重置redis时间5天
                    stringRedisTemplate.expire(ConstantUtil.ADMIN_TOKEN + token, Duration.ofHours(5));
                    return true;
                }
            }
        }

        response.setStatus(401);
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}
